package com.xindaoapp.happypet.fragments;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.text.Html;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.InformMessage;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.TimeFormat;

/**
 * 系统通知
 * 
 * @author chenghao
 * 
 */
public class SystemInformFragment extends BaseFragment {
    private PullToRefreshListView mPullToRefreshListView;
    private InformMessageAdapter mAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_system_inform, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void initEvents(View view) {
        super.initEvents(view);
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        mPullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                onLoadData();
            }
        });
    }

    @Override
    protected void onLoadData() {
        super.onLoadData();
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getInformMessageList(UserState.getUserUid(), Constants.PAGE_FIRST,
                        Constants.PAGE_SIZE, new IRequest<List<InformMessage>>() {

                            @Override
                            public void request(List<InformMessage> t) {
                                if (null != t) {
                                    if (null == mAdapter) {
                                        mAdapter =
                                                new InformMessageAdapter(getActivity(), t,
                                                        Constants.PAGE_SIZE,
                                                        R.layout.item_system_inform,
                                                        R.layout.item_loading);
                                        mPullToRefreshListView.setAdapter(mAdapter);
                                    } else {
                                        mAdapter.setInitData(t);
                                        mAdapter.notifyDataSetChanged();
                                    }
                                    onDataArrived(true);

                                } else {
                                    onDataArrived(false);
                                }
                                mPullToRefreshListView.onRefreshComplete();
                            }
                        });
    }

    /**
     * 通知
     * 
     * @author xindaoapp
     */
    class InformMessageAdapter extends XinDaoBaseAdapter<InformMessage> {

        public InformMessageAdapter(Context context, List<InformMessage> iniData, int pageSize,
                int res, int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public void nextPage(int start, int size,
                final ILoadNextPageData<InformMessage> iLoadNextPageData) {
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getInformMessageList(UserState.getUserUid(), start, size,
                            new IRequest<List<InformMessage>>() {

                                @Override
                                public void request(List<InformMessage> t) {
                                    iLoadNextPageData.loadNextPageData(t);
                                }
                            });
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent,
                final InformMessage value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.time = (TextView) convertView.findViewById(R.id.time);
                holder.content = (TextView) convertView.findViewById(R.id.content);
                convertView.setTag(holder);
            }
            ImageLoader.getInstance().displayImage(value.userface, holder.icon);

            holder.time.setText(TimeFormat.format(CommonUtil
                    .formatTime2Date(value.dateline * 1000l).toString()));

            holder.content.setText(Html.fromHtml(value.note));
            convertView.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    new AlertDialog.Builder(getActivity()).setTitle("消息").setMessage("确认删除？")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定", new OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    delete(position, value.id);
                                }
                            }).create().show();
                    return false;
                }
            });
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView time;
            TextView content;
        }
    }

    private void delete(final int position, String noticeId) {
        HappyPetApplication.get().getMoccaApi()
                .deleteInformMessage(noticeId, new IRequest<Pair<Boolean, String>>() {

                    @Override
                    public void request(Pair<Boolean, String> t) {
                        if (null != t) {
                            if (t.first) {
                                mAdapter.getResult().remove(position);
                                mAdapter.notifyDataSetChanged();
                            }
                            Toast.makeText(getActivity(), t.second, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), R.string.net_error, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                });
    }

    @Override
    protected String getTitleName() {
        return "系统通知";
    }

}
